package com.kitty.record.kittyio.nio.two;

import io.netty.util.internal.SystemPropertyUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @Description
 * @Author SHEN
 * @Date 2021/2/18
 */
public class Client {

    private final String HOST = "127.0.0.1";

    private final int PORT = 9999;

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;

    public Client() throws IOException {

        selector = Selector.open();

        socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));

        socketChannel.configureBlocking(false);

        socketChannel.register(selector, SelectionKey.OP_READ);

        userName = socketChannel.getLocalAddress().toString().substring(1);

        System.out.println(userName+" is ok....");
    }

    public void sendInfo(String info){

        info = userName + "说："+info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void readInfo(){

        try {
            int readChannels = selector.select();

            if(readChannels > 0){

                Iterator<SelectionKey> it = selector.selectedKeys().iterator();

                while(it.hasNext()){


                    SelectionKey sk = it.next();

                    if(sk.isReadable()){

                        SocketChannel sc = (SocketChannel) sk.channel();

                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                        sc.read(byteBuffer);

                        String msg = new String(byteBuffer.array());

                        System.out.println(msg.trim());

                    }
                    it.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {

        Client client = new Client();

        new Thread(()->{
            while (true){
                client.readInfo();
                try {
                    Thread.currentThread().sleep(3000);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()){

            String msg = scanner.nextLine();

            client.sendInfo(msg);

        }

    }

}
